package com.itheima.reggie.service.impl;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.entity.Page;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.exception.BusinessException;
import com.itheima.reggie.mapper.EmployeeMapper;
import com.itheima.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class EmployeeServiceImpl implements EmployeeService {
    @Autowired(required = false)
    private EmployeeMapper employeeMapper;

    @Override
    public R<Employee> selectEmployeeByUsernameAndPassword(Employee employee) {
        Employee loginEmployee = employeeMapper.selectEmployeeByUsernameAndPassword(employee);
        if (employee==null){
            throw new BusinessException("账号或密码错误");
        }

        if (!DigestUtils.md5DigestAsHex(employee.getPassword().getBytes()).equals(loginEmployee.getPassword())){
            throw new BusinessException("账号或密码错误");
        }

        if (loginEmployee.getStatus()==0){
            throw new BusinessException("账号已被封禁,请联系管理员");
        }

        return R.success(loginEmployee);
    }

    @Override
    public Page<Employee> selectByPage(long page, long pageSize, String name) {
        List<Employee> employees = employeeMapper.selectByPage((page - 1) * pageSize, pageSize, name);
        long count = employeeMapper.count(name);
        Page<Employee> employeePage = new Page<>(employees,count,pageSize,page);

        return employeePage;
    }

    @Override
    public R<String> add(Employee employee) {
        Employee employee1 = employeeMapper.selectEmployeeByUsernameAndPassword(employee);
        if (employee1!=null){
            throw new BusinessException("账号已存在,请重试");
        }

        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        employee.setStatus(1);
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());

        employeeMapper.add(employee);

        return R.success("添加成功");
    }

    @Override
    public Boolean update(Employee employee) {
        Integer update = employeeMapper.update(employee);
        return update>0;
    }

    @Override
    public Employee findById(Integer id) {
        Employee byId = employeeMapper.findById(id);
        return byId;
    }
}
